import { toast, createQrcode, wxfileTobase64 } from '../../../utils/util'
import { getQrprojectDetail } from '../../api/long-insure'
import { fastInsureSubtractType } from '../../utils/map.js'
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        detailData: {},
        showHint: true,
        imageUrl: '',
        img: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        this.widget = this.selectComponent('.widget')
        this.setData({
            id: options.id || '',
        })
        // if (this.data.id) {
        //     await this.getDetail()
        // }
    },
    async onShow() {
        if (this.data.id) {
            await this.getDetail()
        }
    },
    async getDetail() {
        const res = await getQrprojectDetail(this.data.id)
        res.typeName = fastInsureSubtractType[res.type]
        this.setData({
            detailData: res,
        })
        await this.createQr()
    },
    async createQr() {
        // const res = await createQrCode({
        //     appId: 'wx850e3a22db40acac',
        //     page: 'pages/fastAddInsuranceStatus/fastAddInsuranceStatus',
        //     scene: `id=${this.data.detailData.id}`,
        //     width: 200,
        // })
        const scene = `id=${this.data.detailData.id}`
        const text = app.globalData.qrCodeUrl + '?qrcodeType=fast-insurance&scene=' + encodeURIComponent(scene)
        const res = await createQrcode('qrcode', text)
        const base64 = await wxfileTobase64(res)
        this.setData({
            imageUrl: 'data:image/png;base64,' + base64,
        })
    },
    onCloseHint() {
        this.setData({
            showHint: false,
        })
    },
    toEdit() {
        wx.navigateTo({
            url: `/packageLongInsure/pages/fast-insure-add/fast-insure-add?id=${this.data.id}`,
        })
    },
    async createImage(canvas, url) {
        return new Promise((resolve) => {
            const image = canvas.createImage()
            image.src = url
            image.onload = () => {
                resolve(image)
            }
        })
    },
    createCanvas() {
        wx.showLoading({
            title: '生成中',
        })
        wx.createSelectorQuery()
            .select('#myCanvas')
            .fields({ node: true, size: true })
            .exec(async (res) => {
                const canvas = res[0].node
                const ctx = canvas.getContext('2d')
                const width = res[0].width
                const height = res[0].height
                const dpr = wx.getWindowInfo().pixelRatio
                canvas.width = width * dpr
                canvas.height = height * dpr
                ctx.scale(dpr, dpr)
                console.log(1000, width, height)
                //  开始绘制
                ctx.clearRect(0, 0, width, height)
                const image = await this.createImage(
                    canvas,
                    'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManagerfbf3e2c8-72dd-4e64-ac86-6a9f4e3198a4.png'
                )
                ctx.drawImage(image, 0, 0, width, height)
                ctx.font = '14px Arial bold'
                ctx.textAlign = 'center'
                ctx.textBaseline = 'middle'
                ctx.fillText(this.data.detailData.projectName, width / 2, 130)
                const qrCode = await this.createImage(
                    canvas,
                    this.data.imageUrl
                )
                ctx.drawImage(qrCode, 80, 180, 180, 180)
                ctx.font = '12px Arial'
                ctx.textAlign = 'center'
                ctx.textBaseline = 'middle'
                ctx.fillText('每小时1至55分钟可扫码投保', width / 2, 390)
                ctx.fillText(
                    '打开微信扫一扫注册子弹工作小程序投保',
                    width / 2,
                    410
                )
                setTimeout(() => {
                    this.canvasToUrl(canvas, width, height)
                }, 100)
            })
    },
    canvasToUrl(canvas, width, height) {
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width,
            height,
            canvas,
            fileType: 'png',
            success: (res) => {
                this.saveCanvas(res.tempFilePath)
            },
            fail: () => {
                wx.hideLoading()
                toast('生成失败，请重新生成')
            },
        })
    },
    saveCanvas(path) {
        wx.saveImageToPhotosAlbum({
            filePath: path,
            success: () => {
                console.log(1111)
                wx.hideLoading()
                toast('保存成功')
            },
            fail: (err) => {
                console.log(2121, err)
            },
        })
    },
    onUnload() {
        const pages = getCurrentPages()
        const listPage = pages[pages.length - 3]
        if (
            listPage &&
            listPage.route === 'packageLongInsure/pages/fast-insure/fast-insure'
        ) {
            listPage.data.pageNum = 1
            listPage.getList()
        }
    },
})
